import prisma from '~/server/database/client'
export async function createTag(data:Omit<Tag, "id">){
  const tag = await prisma.tag.create({ data })
  return tag
}

export async function updateTag(data:Tag){
  const tag = await prisma.tag.update({ where: { id: data.id }, data })
  return tag
}

export async function deleteTag(id:number){
  const currentDate = new Date()
  await prisma.tag.update({
    where: { 
      id 
    },
    data:{ 
      deleted_at: currentDate
    }
  })
}

export async function findTagById(id:number){
  const tag = await prisma.tag.findUnique({ where:{id} })
  return tag
}

export async function findSameNameTag(data:Omit<Tag, "id">|Tag){
  const {kind, name,user_id} = data
  const tag = await prisma.tag.findMany({
    where:{
      name,
      kind,
      user_id,
      deleted_at:null
    }
  })
  return tag.length>0 ? true : false
}

export async function getUserTagsByPage(user_id:number, page:number, kind:TagType){
  const per_page = 25
  const count = await prisma.tag.count({
    where: {
      user_id,
      kind,
      deleted_at: null
    },
  });
  const tags = await prisma.tag.findMany({
    where:{
      user_id,
      kind,
      deleted_at: null
    },
    skip: (page-1)*per_page,
    take: per_page,
  })
  return {
    resources:tags,
    pager:{
      page,
      per_page,
      count,
    }
  }
}
